package com.whiteape.book.utils;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.net.Uri;

import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;

import com.tbruyelle.rxpermissions2.RxPermissions;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.debug.UMLog;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.whiteape.book.R;
import com.whiteape.book.WaApp;
import com.whiteape.book.core.manager.ReadSettingManager;

import gdut.bsx.share2.Share2;
import gdut.bsx.share2.ShareContentType;
import io.reactivex.disposables.Disposable;

public class ShareUtil {

    public static void recordNewShareTime() {
        ReadSettingManager.getInstance().setLastSharedTime(System.currentTimeMillis());
    }

    public static boolean checkIfCanDownload() {
        long lastShareTime = ReadSettingManager.getInstance().getLastSharedTime();
        return System.currentTimeMillis() - lastShareTime < 3 * 24 * 3600 * 1000;
    }

    public static void showShareDialog(Activity activity, UMShareListener umShareListener) {
        if (activity == null) {
            return;
        }
        MobclickAgent.onEvent(activity, "share_show_dialog");
        new AlertDialog.Builder(activity)
                .setTitle(R.string.share)
                .setMessage(activity.getString(R.string.sure_share))
                .setPositiveButton(R.string.wa_common_sure, (dialog, which) -> {
                    MobclickAgent.onEvent(activity, "share_show_dialog_yes");

                    umShare(activity, umShareListener);})
                .setNegativeButton(R.string.wa_common_cancel, (dialogInterface, i) -> {
                    MobclickAgent.onEvent(activity, "share_show_dialog_no");
                })
                .show();
//        ATH.setAlertDialogTint(alertDialog);

    }

    public static void share(Activity activity, int requestCode) {
        if (activity == null) {
            return;
        }
        new Share2.Builder(activity)
                // 指定分享的文件类型
                .setContentType(ShareContentType.IMAGE)
                // 设置要分享的文件 Uri
                .setShareFileUri(Uri.parse("android.resource://" + activity.getApplicationContext().getPackageName() + "/" + R.mipmap.ic_app))
                // 设置分享选择器的标题
                .setTitle(activity.getResources().getString(R.string.share))
                .setOnActivityResult(requestCode)
                .build()
                // 发起分享
                .shareBySystem();
    }

    public static void umShare(Activity activity, UMShareListener umShareListener) {
//        UMWeb umWeb = new UMWeb("https://dibaqu.com/aYbA");
//        umWeb.setTitle(activity.getResources().getString(R.string.app_name));
//        umWeb.setThumb(new UMImage(activity, R.mipmap.ic_app));
//        umWeb.setDescription(activity.getResources().getString(R.string.slogan));
        UMImage image = new UMImage(activity, R.mipmap.share);
        image.setThumb(new UMImage(activity, R.mipmap.ic_app));

        new ShareAction(activity)

                .withText(activity.getResources().getString(R.string.slogan))
                .withMedia(image)
                .setDisplayList(SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE, SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE)
                .setCallback(umShareListener).open();
    }



    /**
     * 分享qq需要sdcard读取权限
     */
    public static void checkPermissionAndShareInFragment(Fragment fragment, UMShareListener listener) {

        if (fragment.getActivity() == null) {
            return;
        }
        RxPermissions rxPermissions = new RxPermissions(fragment.getActivity());
        if (!rxPermissions.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            new AlertDialog.Builder(fragment.getActivity())
                    .setTitle(R.string.wa_common_tip)
                    .setMessage(R.string.permission_request_sdcard)
                    .setPositiveButton(R.string.wa_common_sure, ((dialogInterface, i) -> {
                        dialogInterface.dismiss();
                        rxPermissionRequest(rxPermissions, fragment, listener);
                    }))
                    .setNegativeButton(R.string.wa_common_cancel, ((dialogInterface, i) -> {
                        dialogInterface.dismiss();
                        ToastUtils.show("已经拒绝权限，需要重新打开授权才可以进行分享");
                    })).show();
        } else {

            ShareUtil.umShare(fragment.getActivity(), listener);
//            scanFile();
        }
    }

    private static void rxPermissionRequest(RxPermissions rxPermissions, Fragment fragment, UMShareListener listener) {
        if (fragment.getActivity() == null) {
            return;
        }
        String permissionRequired = Manifest.permission.WRITE_EXTERNAL_STORAGE;
        Disposable disposable = rxPermissions.requestEach(permissionRequired)
                .subscribe(permission -> {
                    if (permission.granted) {
                        // `permission.name` is granted !
//                        scanFile();

                        ShareUtil.umShare(fragment.getActivity(), listener);
                    } else if (permission.shouldShowRequestPermissionRationale) {
                        // Denied permission without ask never again
//                        setResult(Activity.RESULT_CANCELED);
//                        finish();
                    } else {
                        // Denied permission with ask never again
                        // Need to go to the settings
                        if (fragment.getContext() == null) {
                            return;
                        }
                        new AlertDialog.Builder(fragment.getContext())
                                .setTitle(R.string.wa_common_tip)
                                .setMessage(R.string.permission_request_sdcard_goto_setting)
                                .setPositiveButton(R.string.wa_common_sure, ((dialogInterface, i) -> {
                                    //goto setting
                                    dialogInterface.dismiss();
                                    JumpPermissionManagement.goToSetting(fragment.getActivity());
//                                    setResult(RESULT_CANCELED);
//                                    finish();

                                }))
                                .setNegativeButton(R.string.wa_common_cancel, ((dialogInterface, i) -> {
                                    dialogInterface.dismiss();
                                    ToastUtils.show("已拒绝权限，无法继续进行");
//                                    setResult(RESULT_CANCELED);
//                                    finish();
                                })).show();

                    }
                });

    }


}
